import { ReactNode, useState } from 'react';
import { createContext } from 'use-context-selector';
import { useEventEmitter, useRequest } from 'ahooks';
import { EventEmitter } from 'ahooks/lib/useEventEmitter';
import { CollectionEvent, DatasetCollectionSchemaType } from '@/types/dataset';

type CollectionContextType = {
  event$: EventEmitter<CollectionEvent> | null;
  name: string;
  setName: (name: string) => void;
  collectionId: string;
  setCollectionId: (id: string) => void;
  collectionData: DatasetCollectionSchemaType | null;
  setCollectionData:  React.Dispatch<React.SetStateAction<DatasetCollectionSchemaType | null>>;
};

export const CollectionContext = createContext<CollectionContextType>({
  event$: null,
  name: '',
  setName: () => {},
  collectionId: '',
  setCollectionId: () => {},
  collectionData: null,
  setCollectionData: () => {},
});

const CollectionContextProvider = ({ children }: { children: ReactNode }) => {
  const [collectionId, setCollectionId] = useState('');
  const [name, setName] = useState('');
  const [collectionData, setCollectionData] = useState<DatasetCollectionSchemaType | null>(null);
  const event$ = useEventEmitter<CollectionEvent>();

  const handleAddIndex = (index: string) => {
    setCollectionData((prev: DatasetCollectionSchemaType | null) => {
      if (!prev) {
        return null;
      }
      return {
        ...prev,
        indexes: [...(prev.indexes ?? []), index],
      };
    });
  };

  const contextValue: CollectionContextType = {
    event$,
    name,
    setName,
    collectionId,
    setCollectionId,
    collectionData,
    setCollectionData
  };

  return <CollectionContext.Provider value={contextValue}>{children}</CollectionContext.Provider>;
};

export default CollectionContextProvider;
